import store from '../store'
export function createSocket(){
const newWebSocket = {
    websocket: null,
    heartbeat_timer: null, // 用于心跳检测
    active_close: false, // 是否主动关闭
    token:null,
    init: (params) => {
      if(!newWebSocket.token){
        const userInfo = store.getters&&store.getters.getUserInfo
        newWebSocket.token = userInfo.access_token
      }
      newWebSocket.websocket = new WebSocket(`ws://127.0.0.1:9999${params.url}?access_token=${newWebSocket.token}&TENANT-ID=1`)
      newWebSocket.websocket.onopen = (data) => {
        // newWebSocket.heartbeat()
        if (params.onopen) {
          params.onopen('webSocket已连接', data)
        }
      }
      newWebSocket.websocket.onmessage = (data) => {
        if (params.onmessage) {
          // console.log('socket接收消息: ' + JSON.stringify(data.data))
          params.onmessage(data.data)
        }
      }
      newWebSocket.websocket.onclose = (e) => {
        clearInterval(newWebSocket.heartbeat_timer)
        if (newWebSocket.active_close) {
          if (params.onclose) {
            params.onclose('连接已手动关闭')
          }
        } else {
          if (params.onclose) {
            params.onclose('连接已关闭, 正在重连')
              newWebSocket.reconnect(params)
          }
        }
      }
      newWebSocket.websocket.onerror = () => {
        clearInterval(newWebSocket.heartbeat_timer)
        if (params.onerror) {
          params.message('连接发生错误！等待五秒后重连')
          setTimeout(() => {
            newWebSocket.reconnect(params)
          },5000)
        }
      }
    },
    heartbeat: () => {
      console.log('执行心跳')
      if (newWebSocket.heartbeat_timer) {
        clearInterval(newWebSocket.heartbeat_timer)
      }
      newWebSocket.heartbeat_timer = setInterval(function (){
        newWebSocket.websocket.send((JSON.stringify({type: "ping"})))
      },10000)
    },
    reconnect: (params) => {
      console.log('执行重连')
      newWebSocket.active_close = false
      if (newWebSocket.websocket) {
        newWebSocket.websocket.close()
      }
      newWebSocket.heartbeat_timer = setInterval(function (){
        newWebSocket.init(params)
      },5000)
    },
    close: () => {
      console.log('手动关闭，无需重连')
      clearInterval(newWebSocket.heartbeat_timer)
      newWebSocket.active_close = true
      newWebSocket.websocket.close()
    }
  }

  return newWebSocket
}


